from core.config import Config
from core.shop import Shop
from core.order import Order
from core.rider import Rider
from core.result import Result
from core.config_server import ConfigServer

import logging
import datetime
import traceback


def main():
    all_shop_stat()


def all_shop_stat():
    # 初始化配置
    Config.set_config()

    # 找到派单的门店id
    shop_dispatch_mode_dict = Shop.get_shop_dispatch_mode()
    if shop_dispatch_mode_dict is None or len(shop_dispatch_mode_dict) == 0:
        logging.info(f"本次执行失败，没有使用算法的门店")
        return

    s = datetime.datetime.now()

    # 按门店统计数据
    for key, val in shop_dispatch_mode_dict.items():
        shop_id = key
        algo_mode = val
        one_shop_stat(shop_id)

    e = datetime.datetime.now()
    logging.info(f"本次统计结束。门店数:{len(shop_dispatch_mode_dict)}. 耗时:{e.timestamp() - s.timestamp()}s, 开始时间:{s},结束时间:{e}")


def one_shop_stat(shop_id):
    s = datetime.datetime.now()
    try:
        # 获取未来订单数
        order_num_obj = Order.get_order_num(shop_id)

        # 获得未来骑手数
        rider_num_obj = Rider.get_rider_num(shop_id)

        # 插入统计结果
        Result.writer_result_data(shop_id, order_num_obj, rider_num_obj)

        # 获得压力配置百分比
        config_server_obj = ConfigServer.get_config_server_info(shop_id)

        # 将压力值更新到redis
        Result.flush_redis(shop_id, config_server_obj)

        # 删除一个月之前的数据
        Result.delete_one_month_ago_data(shop_id)

    except Exception as e:
        traceback.print_exc()
        logging.error(f"统计异常原因：{e}。门店{shop_id}, 时间:{s}")
    finally:
        e = datetime.datetime.now()
        logging.info(f"门店{shop_id}, 耗时:{e.timestamp() - s.timestamp()}s, 开始时间:{s},结束时间:{e}")


if __name__ == "__main__":
    main()